package org.or5e.oss.web;

import java.io.IOException;
import java.io.PrintStream;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.or5e.oss.core.BaseUtility;

public abstract class BaseServlet extends HttpServlet {
	private ServletConfig config = null;
	private static Properties properties = new Properties();
	private Logger logger = Logger.getLogger(getName());
	static {
		try {
			properties.load(ClassLoader.getSystemResourceAsStream("Resource.properties"));
		}
		catch(IOException _exception) {
			
		}
	}
	public void init(ServletConfig config) throws ServletException{
		super.init(config);
	}
	
	public void doGet(HttpServletRequest _request, HttpServletResponse _response) {
		try {
			PrintStream out = new PrintStream(_response.getOutputStream());
			HttpSession session = _request.getSession(false);
			ServletContext context = getServletContext();
			
			String preProcess = preProcess(_request, session, context, logger, properties);
			String sendTo = process(_request, _response, session, context, config, out, preProcess, logger, properties);
			postProcess(_request, _response, sendTo);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected void postProcess(HttpServletRequest request, HttpServletResponse response, String sendTo) {
		if(BaseUtility.getUtility().isEmptyString(sendTo)) {
			try {
				response.sendRedirect(sendTo);
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	protected abstract String process(HttpServletRequest request,
			HttpServletResponse response, HttpSession session,
			ServletContext context, ServletConfig config, PrintStream out,
			String preProcess, Logger logger, Properties properties);

	protected String preProcess(HttpServletRequest request, HttpSession session,
			ServletContext context, Logger logger, Properties properties) {
		return "";		
	}

	public void doPost(HttpServletRequest _request, HttpServletResponse _response) {
		doGet(_request, _response);
	}

	public abstract String getName();
}
